<template>
  <div class="addHospital">
    <div class="cus-title">
      <h4 v-if="state === 'edit'">编辑医院</h4>
      <h4 v-else>添加医院</h4>
    </div>
    <div class="cus-hearder">
      医院信息
    </div>
    <div class="sub-form">
      <el-form ref="BindForm" :model="hospitalForm" label-width="100px">
        <el-form-item label="医院" required>
          <div class="hospitalInfo">
            <el-form ref="mainBindForm" :model="BindForm" :rules="pattern">
              <el-form-item label="医院名称:" prop="hospitalName" style="margin-bottom: 22px">
                <el-col :span="20" class="hospitalForm">
                  <el-input
                    v-model="BindForm.hospitalName"
                    style="width: 400px"
                    maxlength="20"
                    minlength="1"
                    placeholder="输入医院名称"
                  />
                </el-col>
              </el-form-item>
              <el-form-item label="医院地址：" required style="margin-bottom: 22px">
                <el-col :span="20" class="hospitalForm">
                  <el-col :span="24" style="display: flex">
                    <el-form-item prop="provinceCode" style="padding-left: 0" class="time">
                      <el-select
                        ref="province"
                        v-model="BindForm.provinceCode"
                        @change="handelProvince"
                      >
                        <el-option
                          v-for="(item, index) in pca.province"
                          :key="index"
                          :value="item.code"
                          :label="item.name"
                        /> </el-select></el-form-item>
                    <el-form-item prop="cityCode" class="time">
                      <el-select
                        v-model="BindForm.cityCode"
                        @change="handelCity"
                      >
                        <el-option
                          v-for="(item, index) in pca.forCity"
                          :key="index"
                          :value="item.code"
                          :label="item.name"
                        /> </el-select></el-form-item>
                    <el-form-item prop="areaCode" class="time">
                      <el-select
                        v-model="BindForm.areaCode"
                        @change="handelArea"
                      >
                        <el-option
                          v-for="(item, index) in pca.forArea"
                          :key="index"
                          :value="item.code"
                          :label="item.name"
                        /> </el-select></el-form-item>
                  </el-col>
                </el-col>
              </el-form-item>
              <el-form-item prop="detailAddress" style="margin-bottom: 22px">
                <el-col :span="20" style="margin-left: 140px" class="hospitalForm">
                  <el-amap-search-box
                    ref="searchBox"
                    v-model="BindForm.detailAddress"
                    style="border-radius: 5px; border: 1px solid #F3F3F3;height: 36px;"
                    :search-option="searchOption"
                    :on-search-result="onSearchResult"
                  />
                </el-col>
              </el-form-item>
              <el-form-item style="margin-bottom: 22px">
                <el-col :span="20" style="margin-left: 140px" class="hospitalForm">
                  <el-amap
                    ref="map"
                    vid="amapDemo"
                    :amap-manager="amapManager"
                    :center="center"
                    :zoom="zoom"
                    :plugin="plugin"
                    :events="events"
                    class="amap-demo"
                    style="height:500px;"
                  >
                    <el-amap-marker :position="center" />
                  </el-amap>
                </el-col>
              </el-form-item>
              <el-form-item class="hospitalTable" label="可服务门店:" required style="margin-bottom: 22px">
                <el-col :span="20">
                  <el-table
                    :data="BindData"
                    class="ele-table"
                    :header-cell-style="handleCellStyle"
                  >
                    <el-table-column label="门店名称" prop="storeName" width="200" />
                    <el-table-column label="门店地址" prop="address" width="200" />
                    <el-table-column align="right" label="操作">
                      <template slot-scope="scope">
                        <el-button
                          style="color:red"
                          type="text"
                          @click="storeRemove(scope.row)"
                        >删除</el-button>
                      </template>
                    </el-table-column>
                  </el-table>
                  <el-button
                    type="text"
                    @click="addStore"
                  >添加门店</el-button>
                </el-col>
              </el-form-item>
              <el-form-item label="适用商品:" required style="margin-bottom: 22px">
                <el-col :span="20" class="hospitalForm">
                  <el-card shadow="never">
                    <div class="ele-content">
                      <div>
                        <el-radio
                          v-model="BindForm.goodsType"
                          label="0"
                          @change="changeGoodsType"
                        >支持部分商品</el-radio>
                        <el-radio
                          v-model="BindForm.goodsType"
                          label="1"
                          @change="changeGoodsType"
                        >支持全部商品</el-radio>
                      </div>
                    </div>
                    <div v-if="BindForm.goodsType=='0'">
                      <HospitalPartTable ref="hospitalPartTable" :store-goods-list="storeGoodsList" @changeStoreGoodsList="changeStoreGoodsList" />
                    </div>
                    <div v-else-if="BindForm.goodsType=='1'">
                      <HospitalAllTable ref="hospitalAllTable" :store-goods-list="storeGoodsList" @changeStoreGoodsList="changeStoreGoodsList" />
                    </div>
                  </el-card>
                </el-col>
              </el-form-item>
              <div
                v-if="BindForm.detailAddress && BindData.length >0 && BindForm.goodsType && storeGoodsList.length>0 && getSelfPosition.length >0"
                style="margin-left: -15px;"
              >
                <el-form-item v-for="(item,index) in hospitalPositionList" :key="index">
                  <hospital-position ref="hospitalPosition" :index="index" :self-position-list="getSelfPosition" />
                </el-form-item>
                <el-form-item>
                  <el-button type="text" @click="addHospitalPosition">添加位置</el-button>
                </el-form-item>
              </div>
            </el-form>
          </div>
          <div v-for="(item,index) in branchList" :key="index" class="hospitalInfo">
            <HospitalInfo ref="branchHospital" :index="index" @delBranch="delBranch" />
          </div>
          <el-button type="text" @click="addBranch">添加分院</el-button>
        </el-form-item>
        <el-form ref="deliveryForm" :model="deliveryForm" :rules="rules">
          <el-form-item label="配送方式" prop="deliveryWay">
            <el-col :span="20">
              <el-checkbox-group v-model="deliveryForm.deliveryWay">
                <el-checkbox label="0" disabled checked>小时达</el-checkbox>
                <el-checkbox label="1">预约</el-checkbox>
              </el-checkbox-group>
            </el-col>
            <el-col :span="20">
              <el-col :span="20" class="el-col-offset-2">
                <el-form-item label="加急费用" prop="expeditedCharge" style="margin-bottom: 20px">
                  <el-col :span="20">
                    <el-col :span="10" class="urgent">
                      <el-input-number v-model="deliveryForm.expeditedCharge" :controls="false" :precision="2" :min="0" :max="1000000" placeholder="输入加急费用" />元
                    </el-col>
                  </el-col>
                </el-form-item>
                <el-form-item style="margin-bottom: 20px">
                  <el-col :span="10" style="margin-left: 140px">
                    <el-alert
                      title="该费用为原来的基础上增加的费用。"
                      type="info"
                      :closable="false"
                    />
                  </el-col>
                </el-form-item>
                <el-form-item label="送达时长" prop="deliveryTime" style="margin-bottom: 20px">
                  <el-col :span="20">
                    <el-col :span="10" class="urgent">
                      <el-input-number v-model="deliveryForm.deliveryTime" :controls="false" :precision="0" placeholder="输入送达时长" :min="0" :max="1000" />小时
                    </el-col>
                  </el-col>
                </el-form-item>
                <el-form-item style="margin-bottom: 20px">
                  <el-col :span="20" style="margin-left: 140px">
                    <el-alert
                      title="该时长为送达医院的最晚时长。"
                      type="info"
                      :closable="false"
                    />
                  </el-col>
                </el-form-item>
                <el-form-item v-if="deliveryForm.deliveryWay.indexOf('1')!=-1" label="可预约天数" prop="subscribeDay" style="margin-bottom: 20px">
                  <el-col :span="20">
                    <el-input v-model="deliveryForm.subscribeDay" :controls="false" :precision="0" placeholder="输入天数" :min="0" :max="1000" />
                  </el-col>
                </el-form-item>
                <el-form-item v-if="deliveryForm.deliveryWay.indexOf('1')!=-1" style="margin-bottom: 20px">
                  <el-col :span="20" style="margin-left: 140px">
                    <el-alert
                      title="用户可以选择预约的最晚日期。例：可预约天数为3天，那用户下单时，在选择预约时间为当前时间的后三天。"
                      type="info"
                      :closable="false"
                    />
                  </el-col>
                </el-form-item>
                <div v-if="deliveryForm.deliveryWay.indexOf('1')!=-1" class="appointmentTime">
                  <div v-for="(item,index) in timeList" :key="index">
                    <HospitalTimeInterval ref="hospitalTimeInterval" :form-obj="item" :index="index" @delete="deleteTimeInterval" />
                  </div>
                </div>
                <el-form-item v-if="deliveryForm.deliveryWay.indexOf('1')!=-1">
                  <el-button type="primary" @click="addTimeInterval">添加时间段</el-button>
                </el-form-item>
              </el-col>
            </el-col>
          </el-form-item>
          <el-form-item class="sub-footer">
            <el-button
              v-if="state != 'detail'"
              type="primary"
              @click="handelSubmit"
            >提交</el-button>
          </el-form-item>
        </el-form>
      </el-form>

    </div>
    <add-hospital-store
      ref="AddHospitalStore"
      :visible="visible"
      @handelClose="handelClose"
      @handelAllSelect="handelAllSelect"
    />
  </div>
</template>

<script>
import AddHospitalStore from '@/components/AddHospitalStore'
import { addHospital, getGoodsByIdList, updateHospital } from '@/api/customAPI/shop/hospitalManage'
import HospitalTimeInterval from '@/components/HospitalTimeInterval'
import { Loading } from 'element-ui'
import { getCityList } from '@/api/auth'
import HospitalInfo from '@/components/hospitalInfo'
import HospitalPartTable from '@/components/HospitalPartTable'
import HospitalAllTable from '@/components/HospitalAllTable'
import HospitalPosition from '@/components/HospitalPosition'
import VueAMap from 'vue-amap'
const amapManager = new VueAMap.AMapManager()
export default {
  name: 'AddHospital',
  components: {
    AddHospitalStore,
    HospitalTimeInterval,
    HospitalInfo,
    HospitalPartTable,
    HospitalAllTable,
    HospitalPosition
  },
  data() {
    const self = this
    return {
      visible: false,
      state: '',
      id: null,
      storeList: [],
      selection: [],
      BindData: [],
      storeGoodsList: [],
      pca: {
        // 省区
        province: [],
        // 需要循环遍历的城区和市区
        city: [],
        area: [],
        // 最后拿到的 城区和市区 select 列表
        forCity: [],
        forArea: []
      },
      timeList: [],
      dMode_1: '',
      dMode_2: '',
      unchange: false,
      branchList: [],
      getSelfPosition: [],
      hospitalForm: {
        shopId: localStorage.getItem('shopId')
      },
      hospitalPositionList: [1],
      BindForm: {
        hospitalName: '',
        detailAddress: '',
        proportionalShare: '1',
        dModeTypeId: '',
        custom: '0',
        goodsType: null,
        selectGoodsIds: [],
        dMode: '',
        storeId: '',
        goodsId: '',
        provinceId: '',
        provinceName: '',
        cityId: '',
        cityName: '',
        areaId: '',
        areaName: '',
        provinceCode: '',
        cityCode: '',
        areaCode: ''
      },
      pattern: {
        hospitalName: [
          { required: true, max: 20, message: '请输入医院名称', trigger: 'blur' },
          { max: 20, message: '输入的字符超过20个', trigger: 'change' }
        ],
        expeditedCharge: [
          { required: true, message: '请输入加急费用', trigger: 'blur' }
        ],
        deliveryTime: [
          { required: true, message: '请输入送达时长', trigger: 'blur' }
        ],
        provinceCode: [
          { required: true, message: '请选择省份', trigger: 'change' }
        ],
        cityCode: [{ required: true, message: '请选择市', trigger: 'change' }],
        areaCode: [{ required: true, message: '请选择地区', trigger: 'change' }],
        detailAddress: [
          { required: true, message: '请输入医院具体地址', trigger: 'blur' }
        ]
      },
      /** 高德地图*/
      amapManager,
      zoom: 18,
      markers: [],
      searchOption: {
        city: '杭州',
        citylimit: false
      },
      center: [120.19, 30.26],
      events: {
        init: (o) => {
          o.getCity((result) => {
            console.log(result)
          })
        },
        moveend: () => {},
        zoomchange: () => {},
        click: (e) => {
          const geocoder = new window.AMap.Geocoder({
            radius: 1000,
            extensions: 'all'
          })
          this.center = [e.lnglat.lng, e.lnglat.lat]
          geocoder.getAddress(this.center, function(status, result) { // 根据坐标获取位置
            if (status === 'complete' && result.info === 'OK') {
              self.BindForm.detailAddress = result.regeocode.formattedAddress
              self.$refs.searchBox.keyword = self.BindForm.detailAddress
            }
          })
        }
      },
      plugin: [
        {
          showMarker: true, // 定位成功后在定位到的位置显示点标记，默认：true
          pName: 'Geolocation', // AMap-Geolocation 定位插件
          events: {
            init(o) {
              // getCurrentPosition 获取当前位置的方法
              // 注意 虽然进页面就会调用这个方法，但是data()中center要有默认值，不然会报错
              o.getCurrentPosition((status, result) => {
                if (result && result.position) {
                  const lng = result.position.lng
                  const lat = result.position.lat
                  if (self.center[0] == 120.19 && self.center[1] == 30.26 && !self.BindForm.detailAddress) {
                    self.center = [lng, lat]
                    self.loaded = true
                    self.zoom = 18
                    self.$nextTick()
                  }
                }
              })
            }
          }
        }
      ],
      /** 配送方式加急*/
      deliveryForm: {
        expeditedCharge: '',
        deliveryTime: '',
        villageName: '',
        deliveryWay: [],
        subscribeDay: ''
      },
      rules: {
        subscribeDay: [
          { required: true, message: '请输入预约天数', trigger: 'blur' }
        ],
        deliveryWay: [
          { required: true, message: '请选择至少一个配送方式', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    const params = this.$dd(this.$route.query.p)
    if (!params) {
      this.state = 'add'
    } else {
      this.state = 'edit'
      if (params.hospitalInfo.otherHospital.length > 0) {
        params.hospitalInfo.otherHospital.forEach(item => {
          this.branchList.push(item)
        })
      }
      if (params.hospitalInfo.mainHospital.locationVoList && params.hospitalInfo.mainHospital.locationVoList.length > 0) {
        this.hospitalPositionList = []
        params.hospitalInfo.mainHospital.locationVoList.forEach(inf => {
          this.hospitalPositionList.push(inf)
        })
        console.log(this.hospitalPositionList)
      }
    }
  },
  mounted() {
    const params = this.$dd(this.$route.query.p)
    if (!params) {
      this.state = 'add'
    } else {
      this.state = 'edit'
    }
    this.loadCity()
  },
  methods: {
    /** 初始化信息 */
    inititalInfo() {
      const params = this.$dd(this.$route.query.p)
      if (params) {
        const loadingInstance = Loading.service({ fullscreen: true })
        console.log(params.hospitalInfo)
        this.id = params.hospitalInfo.mainHospital.id
        this.BindForm.hospitalName = params.hospitalInfo.mainHospital.hospitalName
        // 省市区处理
        this.BindForm.provinceCode = params.hospitalInfo.mainHospital.provinceId
          ? params.hospitalInfo.mainHospital.provinceId
          : ''
        this.BindForm.cityCode = params.hospitalInfo.mainHospital.cityId
          ? params.hospitalInfo.mainHospital.cityId
          : ''
        this.BindForm.areaCode = params.hospitalInfo.mainHospital.villageId
          ? params.hospitalInfo.mainHospital.villageId
          : ''
        /* console.log(this.pca.province)*/
        this.BindForm.provinceId = this.pca.province.find(inf => {
          return inf.code === this.BindForm.provinceCode
        }).id
        this.BindForm.provinceName = this.pca.province.find(inf => {
          return inf.code === this.BindForm.provinceCode
        }).name
        this.pca.city.forEach(inf => {
          if (inf.pid === this.BindForm.provinceId) {
            this.pca.forCity.push(inf)
          }
        })
        this.BindForm.cityId = this.pca.city.find(inf => {
          return inf.code === this.BindForm.cityCode
        }).id
        this.BindForm.cityName = this.pca.city.find(inf => {
          return inf.code === this.BindForm.cityCode
        }).name
        this.pca.area.forEach(inf => {
          if (inf.pid === this.BindForm.cityId) {
            this.pca.forArea.push(inf)
          }
        })
        this.BindForm.areaId = this.pca.area.find(inf => {
          return inf.code === this.BindForm.areaCode
        }).id
        this.BindForm.areaName = this.pca.area.find(inf => {
          return inf.code === this.BindForm.areaCode
        }).name
        this.BindForm.detailAddress = params.hospitalInfo.mainHospital.addressDetail
        this.center = [params.hospitalInfo.mainHospital.lng, params.hospitalInfo.mainHospital.lat]
        this.BindData = params.hospitalInfo.mainHospital.storeList
        if (params.hospitalInfo.mainHospital.goodsType === 0) {
          this.BindForm.goodsType = '0'
        } else {
          this.BindForm.goodsType = '1'
        }
        if (this.BindData.length > 0) {
          this.goodsList = []
          const ids = this.BindData.map(info => info.id)
          getGoodsByIdList({
            storeIdList: ids,
            page: 1,
            limit: 0
          }).then(inf => {
            const _storeGoodsList = []
            inf.data.data.data.forEach(item => {
              _storeGoodsList.push({
                goodsId: item.goodsId,
                customDivide: item.customDivide,
                goodsName: item.goodsName,
                goodsPic: item.goodsPic,
                storeName: item.storeName,
                storeId: item.storeId,
                storeGoodsId: item.storeGoodsId,
                isHospital: 0,
                hospitalSend: [],
                isCareWorker: 0,
                carerSend: [],
                goodsType: item.goodsType
              })
            })
            const goodsIdList = params.hospitalInfo.mainHospital.goodsIds.split(',')

            const goodsList = params.hospitalInfo.mainHospital.goodsList
            this.selection = []
            this.getSelfPosition = []
            _storeGoodsList.forEach(item => {
              goodsList.forEach(info => {
                if (info.id == item.goodsId) {
                  console.log(info)
                  item.isHospital = info.hospitalShow.toString()
                  item.hospitalSend = info.hospitalSend.split(',')
                  item.isCareWorker = info.carerShow.toString()
                  item.carerSend = info.carerSend.split(',')
                  console.log(item)
                  if (info.hospitalShow == 1 && info.hospitalSend.split(',').includes('1')) {
                    this.getSelfPosition.push(item.storeGoodsId)
                  }
                }
              })

              goodsIdList.forEach(inf => {
                if (item.goodsId == inf) {
                  this.selection.push({
                    goodsId: item.goodsId,
                    hospitalShow: item.isHospital,
                    hospitalSend: item.hospitalSend,
                    carerShow: item.isCareWorker,
                    carerSend: item.carerSend
                  })
                }
              })
            })
            this.storeGoodsList = _storeGoodsList
            console.log(_storeGoodsList)
            this.$nextTick(() => {
              this.$refs.searchBox.keyword = this.BindForm.detailAddress
              if (this.BindForm.goodsType == '0') {
                this.$refs.hospitalPartTable.setData(goodsIdList, _storeGoodsList)
              }
            })
            if (this.hospitalPositionList.length > 0) {
              this.$nextTick(() => {
                this.$refs.hospitalPosition.forEach((item, index) => {
                  item.setData(this.hospitalPositionList[index])
                })
              })
            }
          })
        }

        if (params.hospitalInfo.otherHospital.length > 0) {
          this.$nextTick(() => {
            this.$refs.branchHospital.forEach((item, index) => {
              item.inititalInfo(params.hospitalInfo.otherHospital[index])
            })
          })
        }
        this.deliveryForm.expeditedCharge = params.hospitalInfo.deliveryType.urgentCost
        this.deliveryForm.deliveryTime = params.hospitalInfo.deliveryType.deliveryTime
        if (params.hospitalInfo.deliveryType.subscribe == 1) {
          this.deliveryForm.deliveryWay.push('1')
          if (params.hospitalInfo.deliveryType.timePeriods && params.hospitalInfo.deliveryType.timePeriods.length > 0) {
            this.timeList = params.hospitalInfo.deliveryType.timePeriods
          }
          if (params.hospitalInfo.deliveryType.subscribeDay) {
            this.deliveryForm.subscribeDay = params.hospitalInfo.deliveryType.subscribeDay
          }
        }
        loadingInstance.close()
      }
    },
    /** 删除服务门店 */
    storeRemove(row) {
      this.BindData.forEach((item, index) => {
        if (item.id === row.id) {
          this.BindData.splice(index, 1)
        }
      })
      if (this.BindData && this.BindData.length > 0) {
        this.getStoreGoodsList()
      } else {
        this.storeGoodsList = []
      }
    },
    handelAllSelect(list) {
      if (list.length > 0) {
        this.BindData = []
        list.forEach(row => {
          this.BindData.push({
            id: row.id,
            storeName: row.storeName,
            address: row.address
          })
        })
        this.getStoreGoodsList()
        this.handelClose()
      }
    },
    changedAddress() {
      const vm = this
      if (vm.BindForm.address.province && vm.BindForm.address.city) {
        vm.province = vm.BindForm.address.province.code
        vm.city = vm.BindForm.address.city.code
        this.$refs.AddHospitalStore.getProvinceAndCity(vm.province, vm.city)
      }
      if (vm.BindForm.address.province) {
        vm.BindForm.provinceName = vm.BindForm.address.province.name
        vm.BindForm.cityName = ''
        vm.BindForm.villageName = ''
        vm.addressName()
      }
      if (vm.BindForm.address.city) {
        vm.BindForm.cityName = vm.BindForm.address.city.name
        vm.BindForm.villageName = ''
        vm.addressName()
      }
      if (vm.BindForm.address.village) {
        vm.BindForm.villageName = vm.BindForm.address.village.name
        vm.addressName()
      }
    },
    changeGoodsType() {
      this.getStoreGoodsList()
      this.changeStoreGoodsList(this.storeGoodsList)
    },
    /** 根据门店商品到院自提*/
    changeStoreGoodsList(list) {
      console.log(this.hospitalPositionList)
      this.getSelfPosition = []
      console.log(list)
      if (list.length > 0) {
        list.forEach(item => {
          if (item.hospitalSend.includes('1')) {
            this.getSelfPosition.push(item.storeGoodsId)
          }
        })
        this.$nextTick(() => {
          this.$refs.hospitalPosition.forEach(item => {
            item.setData({
              id: null,
              locationName: null,
              startHour: null,
              endHour: null,
              remark: null,
              imgs: [],
              hpFlag: '0',
              inventoryFlag: '0',
              freeFlag: '0',
              adminPhone: '',
              hospitalSelfLocationEquList: []
            })
          })
        })
      }
    },
    /** 添加自提位置*/
    addHospitalPosition() {
      this.hospitalPositionList.push(1)
      this.$nextTick(() => {
        this.$refs.hospitalPosition.forEach((item, index) => {
          if (index == (this.hospitalPositionList.length - 1)) {
            item.setData({
              id: null,
              locationName: null,
              startHour: null,
              endHour: null,
              remark: null,
              imgs: [],
              hpFlag: '0',
              inventoryFlag: '0',
              freeFlag: '0',
              adminPhone: '',
              hospitalSelfLocationEquList: []
            })
          }
        })
      })
    },
    /** 门店商品选择 */
    /* selectGoods(v) {
      console.log(v)
      this.selection = []
      v.forEach(item => {
        this.selection.push({
          goodsId: item.goodsId,
          hospitalShow: item.isHospital ? 1 : 0,
          carerShow: item.isCareWorker ? 1 : 0
        })
      })
      console.log(this.selection)
    },*/
    /** 商品列表勾选状态变化*/
    /* changeIsHospital(data) {
      if (this.selection.length > 0) {
        const list = []
        this.selection.forEach(item => {
          list.push(item.goodsId)
          if (item.goodsId == data.goodsId) {
            item.hospitalShow = data.isHospital ? 1 : 0
          }
        })
        if (!list.includes(data.goodsId)) {
          this.storeGoodsList.forEach(item => {
            if (item.goodsId == data.goodsId) {
              item.isHospital = false
            }
          })
          return this.$message.error('选中该商品后再勾选医院推广')
        }
      } else {
        data.isHospital = false
        return this.$message.error('请先选中该商品')
      }
    },*/
    /** 商品列表勾选状态变化*/
    /* changeIsCareWorker(data) {
      if (this.selection.length > 0) {
        const list = []
        this.selection.forEach(item => {
          list.push(item.goodsId)
          if (item.goodsId == data.goodsId) {
            item.carerShow = data.isCareWorker ? 1 : 0
          }
        })
        if (!list.includes(data.goodsId)) {
          this.storeGoodsList.forEach(item => {
            if (item.goodsId == data.goodsId) {
              item.isCareWorker = false
            }
          })
          return this.$message.error('选中该商品后再勾选医院推广')
        }
      } else {
        data.isCareWorker = false
        return this.$message.error('请先选中该商品')
      }
    },*/
    /** 添加门店 */
    addStore() {
      if (this.BindForm.provinceCode && this.BindForm.cityCode) {
        this.visible = true
        if (this.BindData.length > 0) {
          this.$refs.AddHospitalStore.setSelectList(this.BindData)
        }
        this.$refs.AddHospitalStore.getProvinceAndCity(this.BindForm.provinceCode, this.BindForm.cityCode)
        this.$refs.AddHospitalStore.resetForm()
      } else {
        this.$message.error('请选择医院省份和城市')
      }
    },
    /** 根据门店列表获取商品列表*/
    getStoreGoodsList() {
      if (this.BindData.length > 0) {
        this.storeGoodsList = []
        const ids = this.BindData.map(info => info.id)
        getGoodsByIdList({
          storeIdList: ids,
          page: 1,
          limit: 0
        }).then(inf => {
          inf.data.data.data.forEach(item => {
            console.log(item)
            this.storeGoodsList.push({
              goodsId: item.goodsId,
              customDivide: item.customDivide,
              goodsName: item.goodsName,
              goodsPic: item.goodsPic,
              storeId: item.storeId,
              storeGoodsId: item.storeGoodsId,
              storeName: item.storeName,
              isHospital: 0,
              isCareWorker: 0,
              hospitalSend: [],
              carerSend: [],
              goodsType: item.goodsType
            })
          })
        })
      }
    },
    /** 添加时间段*/
    addTimeInterval() {
      if (this.timeList.length > 0) {
        if (this.$refs.hospitalTimeInterval[this.timeList.length - 1].getData().endTime == '24:00') {
          this.$message.warning('最晚结束时间为24:00')
          return
        } else {
          this.timeList.push({ startTime: null, endTime: null, cost: null })
          if (this.timeList.length > 1) {
            this.$nextTick(() => {
              this.$refs.hospitalTimeInterval[this.timeList.length - 1].setMinTime(this.$refs.hospitalTimeInterval[this.timeList.length - 2].getData().endTime)
              this.$refs.hospitalTimeInterval[this.timeList.length - 2].setDisabled(true)
            })
          }
        }
      } else {
        this.timeList.push({ startTime: null, endTime: null, cost: null })
      }
    },
    /** 删除时间段*/
    deleteTimeInterval(index) {
      this.timeList.splice(index, 1)
      if (this.timeList.length >= 1) {
        this.$refs.hospitalTimeInterval[this.timeList.length - 1].setDisabled(false)
      }
    },
    /** 提交 */
    handelSubmit() {
      if (!this.BindForm.hospitalName) {
        this.$message.error('医院主院名称不能为空')
        return
      }
      if (!this.BindForm.provinceCode) {
        this.$message.error('医院主院所在省份不能为空')
        return
      }
      if (!this.BindForm.cityCode) {
        this.$message.error('医院主院所在市不能为空')
        return
      }
      if (!this.BindForm.areaCode) {
        this.$message.error('医院主院所在地区不能为空')
        return
      }
      if (!this.BindForm.detailAddress) {
        this.$message.error('医院主院所在具体地址不能为空')
        return
      }
      if (this.center[0] == 120.19 && this.center[1] == 30.26) {
        this.$message.error('请重新选择医院主院附近的坐标点')
        return
      }
      if (this.BindData.length === 0) {
        this.$message.error('医院主院未添加服务门店')
        return
      }

      this.$nextTick(() => {
        if (this.BindForm.goodsType == '0') {
          if (this.$refs.hospitalPartTable.getData()) {
            this.selection = this.$refs.hospitalPartTable.getData()
          }
        } else {
          if (this.$refs.hospitalAllTable.getData()) {
            this.selection = this.$refs.hospitalAllTable.getData()
          }
        }
        console.log(this.selection)
        if (this.selection.length === 0) {
          this.$message.error('医院主院未添加适用商品')
          return
        }
        if (this.selection.length > 0) {
          for (let i = 0; i < this.selection.length; i++) {
            if (this.selection[i].carerShow == 0 && this.selection[i].hospitalShow == 0) {
              this.$message.error('医院主院商品至少勾选一个推广类型')
              return
            }
            if (this.selection[i].hospitalShow == 1 && !this.selection[i].hospitalSend) {
              this.$message.error('医院主院商品勾选医院时，至少选择一个医院配送方式')
              return
            }
            if (this.selection[i].carerShow == 1 && !this.selection[i].carerSend) {
              this.$message.error('医院主院商品勾选护工或其他时，至少选择一个护工配送方式')
              return
            }
          }
        }
        const hospitalSelfLocation = []
        if (this.getSelfPosition > 0 && this.hospitalPositionList.length > 0) {
          this.$refs.hospitalPosition.forEach(item => {
            if (item.getData()) {
              hospitalSelfLocation.push(item.getData())
            }
          })
        }
        console.log(hospitalSelfLocation)
        if (!this.deliveryForm.expeditedCharge) {
          this.$message.error('加急费用不能为空')
          return
        }
        if (!this.deliveryForm.deliveryTime) {
          this.$message.error('送达时长不能为空')
          return
        }
        if (this.deliveryForm.deliveryWay.indexOf('1') != -1) {
          if (!this.deliveryForm.subscribeDay) {
            this.$message.error('预约时间不能为空')
            return
          }
          if (this.timeList.length == 0) {
            this.$message.error('预约时间段不能为空')
            return
          } else if (this.timeList.length > 0) {
            for (let i = 0; i < this.timeList.length; i++) {
              if (!this.$refs.hospitalTimeInterval[i].getData().startTime) {
                return this.$message.error('第' + (i + 1) + '个时间的开始时间不能为空')
              }
              if (!this.$refs.hospitalTimeInterval[i].getData().endTime) {
                return this.$message.error('第' + (i + 1) + '个时间的结束时间不能为空')
              }
              if (!this.$refs.hospitalTimeInterval[i].getData().cost) {
                return this.$message.error('第' + (i + 1) + '个时间段的增加额外费用不能为空')
              }
              if (!/^((\d|[1-9]\d+)|\.\d{1,2}|(\d|[1-9]\d+)\.\d{1,2})$/g.test(this.$refs.hospitalTimeInterval[i].getData().cost)) {
                return this.$message.warning('第' + (i + 1) + '个时间段的增加额外费用格式不正确')
              } else if (/^((\d|[1-9]\d+)|\.\d{1,2}|(\d|[1-9]\d+)\.\d{1,2})$/g.test(this.$refs.hospitalTimeInterval[i].getData().cost) && this.$refs.hospitalTimeInterval[i].getData().cost > 100000) {
                return this.$message.warning('第' + (i + 1) + '个时间段的增加额外费用不能大于100000')
              } else if (/^((\d|[1-9]\d+)|\.\d{1,2}|(\d|[1-9]\d+)\.\d{1,2})$/g.test(this.$refs.hospitalTimeInterval[i].getData().cost) && this.$refs.hospitalTimeInterval[i].getData().cost <= 0) {
                return this.$message.warning('第' + (i + 1) + '个时间段的增加额外费用必须大于0')
              }
            }
          }
        }
        const storeList = []
        const storeIds = []
        this.BindData.forEach(item => {
          storeList.push({
            storeId: item.id,
            sendType: 1
          })
          storeIds.push(item.id)
        })

        const timePeriods = []
        if (this.$refs.hospitalTimeInterval && this.timeList.length > 0) {
          this.$refs.hospitalTimeInterval.forEach((item, index) => {
            timePeriods.push(item.getData())
          })
        }
        const hospitalList = []
        if (this.branchList.length > 0) {
          for (let i = 0; i < this.$refs.branchHospital.length; i++) {
            if (this.$refs.branchHospital[i].getData()) {
              hospitalList.push(this.$refs.branchHospital[i].getData())
            } else {
              return
            }
          }
        }
        if (this.state == 'add') {
          const data = {
            mainHospital: {
              hospitalName: this.BindForm.hospitalName,
              provinceId: this.BindForm.provinceCode,
              cityId: this.BindForm.cityCode,
              villageId: this.BindForm.areaCode,
              province: this.BindForm.provinceName,
              city: this.BindForm.cityName,
              village: this.BindForm.areaName,
              addressDetail: this.BindForm.detailAddress,
              storeIds: storeIds.toString(),
              storeData: storeList,
              goodsType: this.BindForm.goodsType === '0' ? 0 : 1,
              goodsData: this.selection,
              lng: this.center[0],
              lat: this.center[1]
            },
            otherHospital: hospitalList,
            /* onlyToHospital: this.BindForm.onlyToHospital == '0' ? 0 : 1,*/
            deliveryType: {
              urgentCost: this.deliveryForm.expeditedCharge,
              deliveryTime: this.deliveryForm.deliveryTime,
              shopId: localStorage.getItem('shopId'),

              hourReach: 1,
              subscribe: this.deliveryForm.deliveryWay.includes('1') ? 1 : 0
            }

          }
          if (this.deliveryForm.deliveryWay.includes('1')) {
            data['deliveryType']['subscribeDay'] = this.deliveryForm.subscribeDay
            data['deliveryType']['timePeriods'] = timePeriods
          }
          if (this.getSelfPosition > 0 && this.hospitalPositionList.length > 0) {
            data['mainHospital']['hospitalSelfLocation'] = hospitalSelfLocation
          }
          const list = []
          if (this.getSelfPosition > 0 && this.hospitalPositionList.length > 0) {
            hospitalSelfLocation.forEach(item => {
              if (item.hospitalSelfLocationEquList) {
                item.hospitalSelfLocationEquList.forEach(inf => {
                  inf.equIdArray.split(',').forEach(info => {
                    list.push(info)
                  })
                })
              }
            })
          }

          if (this.branchList.length > 0) {
            hospitalList.forEach(item => {
              if (item['hospitalSelfLocation']) {
                item['hospitalSelfLocation'].forEach(info => {
                  if (info['hospitalSelfLocationEquList']) {
                    info.hospitalSelfLocationEquList.forEach(inf => {
                      inf.equIdArray.split(',').forEach(iof => {
                        list.push(iof)
                      })
                    })
                  }
                })
              }
            })
          }
          if ((new Set(list)).size != list.length) {
            return this.$message.error('请检查重复编号！')
          }
          const loadingInstance = Loading.service({ fullscreen: true })
          addHospital(data)
            .then(result => {
              loadingInstance.close()
              this.$store.dispatch('tagsView/delView', this.$route)
              this.$message.success('添加成功')
              this.$router.go(-1)
            })
            .catch(err => {
              loadingInstance.close()
              console.log(err)
            })
        } else if (this.state === 'edit') {
          const data = {
            mainHospital: {
              id: this.id,
              hospitalName: this.BindForm.hospitalName,
              provinceId: this.BindForm.provinceCode,
              cityId: this.BindForm.cityCode,
              villageId: this.BindForm.areaCode,
              province: this.BindForm.provinceName,
              city: this.BindForm.cityName,
              village: this.BindForm.areaName,
              addressDetail: this.BindForm.detailAddress,
              storeIds: storeIds.toString(),
              storeData: storeList,
              goodsType: this.BindForm.goodsType === '0' ? 0 : 1,
              goodsData: this.selection,
              lng: this.center[0],
              lat: this.center[1]
            },
            otherHospital: hospitalList,
            /* onlyToHospital: this.BindForm.onlyToHospital == '0' ? 0 : 1,*/
            deliveryType: {
              urgentCost: this.deliveryForm.expeditedCharge,
              deliveryTime: this.deliveryForm.deliveryTime,
              shopId: localStorage.getItem('shopId'),

              hourReach: 1,
              subscribe: this.deliveryForm.deliveryWay.includes('1') ? 1 : 0
            }

          }
          if (this.deliveryForm.deliveryWay.includes('1')) {
            data['deliveryType']['subscribeDay'] = this.deliveryForm.subscribeDay
            data['deliveryType']['timePeriods'] = timePeriods
          }
          if (this.getSelfPosition > 0 && this.hospitalPositionList.length > 0) {
            data['mainHospital']['hospitalSelfLocation'] = hospitalSelfLocation
          }
          const list = []
          if (this.getSelfPosition > 0 && this.hospitalPositionList.length > 0) {
            hospitalSelfLocation.forEach(item => {
              if (item.hospitalSelfLocationEquList) {
                item.hospitalSelfLocationEquList.forEach(inf => {
                  inf.equIdArray.split(',').forEach(info => {
                    list.push(info)
                  })
                })
              }
            })
          }

          if (this.branchList.length > 0) {
            hospitalList.forEach(item => {
              if (item['hospitalSelfLocation']) {
                item['hospitalSelfLocation'].forEach(info => {
                  if (info['hospitalSelfLocationEquList']) {
                    info.hospitalSelfLocationEquList.forEach(inf => {
                      inf.equIdArray.split(',').forEach(iof => {
                        list.push(iof)
                      })
                    })
                  }
                })
              }
            })
          }
          if ((new Set(list)).size != list.length) {
            return this.$message.error('请检查重复编号！')
          }
          const loadingInstance = Loading.service({ fullscreen: true })
          updateHospital(data)
            .then(result => {
              loadingInstance.close()
              this.$store.dispatch('tagsView/delView', this.$route)
              this.$message.success('编辑成功')
              this.$router.go(-1)
            })
            .catch(err => {
              loadingInstance.close()
              console.log(err)
            })
        }
      })
    },
    /** 区 */
    handelArea(v) {
      console.log(v, '区id')
      if (v) {
        this.BindForm.areaName = this.pca.area.find(inf => {
          return inf.code === v
        }).name
        this.BindForm.areaId = this.pca.area.find(inf => {
          return inf.code === v
        }).code
        this.addressName()
      }
    },
    /** 市 */
    handelCity(v) {
      if (v) {
        this.pca.forArea = []
        this.BindForm.areaName = ''
        this.BindForm.areaId = ''
        this.BindForm.areaCode = null
        this.BindData = []
        this.storeGoodsList = []
        const cityInfo = this.$XEUtils.find(this.pca.city, item => item.code === v)
        this.pca.area.forEach(inf => {
          if (inf.pid === cityInfo.id) {
            this.pca.forArea.push(inf)
          }
        })
        this.BindForm.cityName = this.pca.city.find(inf => {
          return inf.code === v
        }).name
        this.BindForm.cityId = this.pca.city.find(inf => {
          return inf.code === v
        }).code
        this.addressName()
        if (this.BindForm.provinceCode && this.BindForm.cityCode) {
          this.$refs.AddHospitalStore.getProvinceAndCity(this.BindForm.provinceCode, this.BindForm.cityCode)
        }
      }
    },
    /** 省 */
    handelProvince(v) {
      this.pca.forCity = []
      this.pca.forArea = []
      this.BindForm.cityId = ''
      this.BindForm.areaId = ''
      this.BindForm.cityCode = null
      this.BindForm.areaCode = null
      this.BindData = []
      this.storeGoodsList = []
      if (v) {
        const provinceInfo = this.$XEUtils.find(this.pca.province, item => item.code === v)
        this.pca.city.forEach(inf => {
          if (inf.pid === provinceInfo.id) {
            this.pca.forCity.push(inf)
          }
        })

        this.BindForm.cityName = ''
        this.BindForm.areaName = ''
        this.BindForm.detailAddress = ''
        this.BindForm.provinceName = this.pca.province.find(inf => {
          return inf.code === v
        }).name
        this.BindForm.provinceId = this.pca.province.find(inf => {
          return inf.code === v
        }).id
        this.BindForm.provinceCode = this.pca.province.find(inf => {
          return inf.code === v
        }).code
        this.addressName()
      }
    },
    addressName() {
      this.BindForm.detailAddress = ''
      this.BindForm.detailAddress =
        this.BindForm.provinceName +
        this.BindForm.cityName +
        this.BindForm.areaName
    },
    /** 修改时初始化 */
    provinceCity() {
      this.pca.forCiry = []
      this.pca.forArea = []
      this.pca.city.forEach(inf => {
        if (inf.pid === this.BindForm.provinceCode) {
          this.pca.forCiry.push(inf)
        }
      })
      this.pca.area.forEach(inf => {
        if (inf.pid === this.BindForm.cityCode) {
          this.pca.forArea.push(inf)
        }
      })
    },
    /** 初始地址 */
    loadCity() {
      getCityList()
        .then(result => {
          this.pca.province = []
          this.pca.city = []
          this.pca.area = []
          result.data.data.forEach(inf => {
            this.pca.province.push(inf.province)
            inf.cityRegion.forEach(reg => {
              this.pca.city.push(reg.city) // 拿市区
              reg.village.forEach(vil => {
                this.pca.area.push(vil) // 拿城区
              })
            })
          })
          this.inititalInfo()
        })
        .catch(err => {
          console.log(err)
        })
    },
    handelClose() {
      this.visible = false
    },
    /** 添加分院*/
    addBranch() {
      this.branchList.push(1)
    },
    /** 删除分院*/
    delBranch(index) {
      this.branchList.splice(index, 1)
    },
    /* handelAddRows(row) {
      console.log(row)
      if (this.BindData.length > 0) {
        this.BindData.forEach(inf => {
          console.log(inf)
          if (inf.id === row.goodsId) {
            return this.$message.warning('已存在')
          } else {
            this.BindData.push({
              id: row.goodsId,
              picUrl: row.goodsImg,
              name: row.goodsName,
              state: row.state,
              goodsType: row.type
            })
            if (this.BindForm.goodsType.toString() === '1') {
              this.getCommodityList()
            }
            this.visible = false
          }
        })
      } else {
        this.BindData.push({
          id: row.goodsId,
          picUrl: row.goodsImg,
          name: row.goodsName,
          state: row.state,
          goodsType: row.type
        })
        this.getCommodityList()
        this.visible = false
      }
    },*/
    handleCellStyle({ row, column, rowIndex, columnIndex }) {
      if (rowIndex === 0) {
        return 'background:#f3f3f3'
      } else {
        return ''
      }
    },
    /** 点击搜索后触发的事件 */
    onSearchResult(pois) {
      if (pois.length > 0) {
        pois.forEach(item => {
          if (this.$refs.searchBox.keyword == item.name) {
            this.center = [item.lng, item.lat]
          } else {
            // 这边类似模糊查询 会返回一个数组，我就直接取第一个值了。
            this.center = [pois[0].lng, pois[0].lat]
          }
        })
      }
      this.BindForm.detailAddress = this.$refs.searchBox.keyword
    }
    /** 获取商品列表 */
    /* getCommodityList() {
      const list = []
      this.BindData.forEach(inf => {
        list.push(inf.id)
      })
      getGoodsByIdList({
        storeIdList: list,
        page: 1,
        limit: 0
      })
        .then(result => {
          this.goodsList = result.data.data
        })
        .catch(err => {
          console.log(err)
        })
    }*/
  }
}
</script>

<style lang="scss" scoped>
.addHospital {
  min-width: 1710px;
  padding: 50px 100px;
  .cus-hearder {
    font-size: 0.9rem;
    height: 50px;
    border-radius: 5px;
    line-height: 50px;
    padding: 0px 20px;
    background: #f3f3f3;
  }
  .sub-form {
    .hospitalInfo {
      width: 100%;
      border: 1px solid #ECECEC;
      border-radius: 5px;
      margin-bottom: 22px;
      .el-form-item .el-form-item {
        margin-bottom: 22px;
      }
    }
    ::v-deep.el-form {
      margin-top: 40px;
      .el-form-item__label {
        width: 140px;
        text-align: start;
      }
      .el-form-item__error {
        margin-left: 140px;
      }
      .el-form-item {
        padding-left: 20px;
        .hospitalForm {
          .el-input {
            width: 126px;
          }
        }
        .baidu-map {
          width: 100%;
          height: 400px;
        }
        .hospitalTable {
          .ele-table {
            width: 900px;
            .cus-column-commodity {
              display: flex;
              align-items: flex-start;

              .left {
                width: 60px;
                height: 60px;
              }
              .right {
                margin-left: 30px;
                display: flex;
                flex-direction: column;
                span:last-child {
                  font-size: 0.7rem;
                  color: gray;
                }
              }
            }
          }
        }
        .el-card {
          width: 900px;
          .card-header {
            display: flex;
            align-items: center;
            .el-button {
              height: 28px;
            }
            .el-input {
              width: 100px;
              margin: 0px 10px;
            }
          }
        }
      }
      .urgent {
        .el-input {
          width: auto;
        }
      }
      .sub-footer {
        .el-button {
          margin-left: 140px;
          width: 100px;
          margin-top: 40px;
        }
      }
    }
    .time {
      ::v-deep .el-form-item__error {
        margin-left: 0 !important;
      }
    }
  }
}
</style>
